var setting={
    async: {
        dataType: 'json',
        dataFilter: function (treeId, treeNode, response) {
            if (response.success) {
                var list = response.entity;
                if(list!=null && list.length>0){
                    $.each(list,function (index,em) {
                        if(em.status==2){
                            em.subjectName = em.subjectName+'(禁用)';
                            list[index] = em;
                        }
                        em.open = true;
                        list[index] = em;
                    });
                }
                return list;
            } else {
                icModale(0, response.message);
            }
        },
        enable: true,
        type: 'post',
        url: baseloaction+'/admin/manage/subject/ajax/ajaxSubjectList'
    },
    view: {
        addHoverDom:function (treeId,treeNode) {//自定义添加按钮
            var sObj = $("#" + treeNode.tId + "_span");

            var preNode = treeNode.getPreNode();
            if(preNode !=null && $("#upBtn_"+treeNode.tId).length <= 0) {//前一个节点存在
                var upStr = "<span class='button up' id='upBtn_" + treeNode.tId + "' title='向上' onfocus='this.blur();'></span>";
                sObj.after(upStr);
                var upBtn = $("#upBtn_" + treeNode.tId);
                if(upBtn){
                    upBtn.bind("click",function () {
                        var preSort = preNode.sort;
                        var currentSort = treeNode.sort;
                        updateNodeSort(treeNode.id,preSort,preNode.id,currentSort,1);
                    });
                }
            }

            //获取下一下节点
            var nextNode = treeNode.getNextNode();
            if(nextNode !=null && $("#downBtn_"+treeNode.tId).length <= 0 ) {//下一下节点存在
                var downStr = "<span class='button down' id='downBtn_" + treeNode.tId + "' title='向下' onfocus='this.blur();'></span>";
                sObj.after(downStr);
                var downBtn = $("#downBtn_" + treeNode.tId);
                if(downBtn){
                    downBtn.bind("click",function () {
                        var downSort = nextNode.sort;
                        var currentSort = treeNode.sort;
                        updateNodeSort(treeNode.id,downSort,nextNode.id,currentSort,2);
                    });
                }
            }
            if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0 || treeNode.parentId>0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加科目' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(){
                initUpdateOrAdd(treeNode.id,0);
                return false;
            });
        },
        removeHoverDom:function(treeId, treeNode) {//鼠标离开删除自定义按钮
            $("#addBtn_"+treeNode.tId).unbind().remove();
            $("#upBtn_" + treeNode.tId).unbind().remove();
            $("#downBtn_" + treeNode.tId).unbind().remove();
        },
        showLine:true,
        selectedMulti: false,
        nameIsHTML:true,
        fontCss:function (treeId,treeNode) {
            if(typeof treeNode.highlight=='undefined' || treeNode.highlight==false){
                if(treeNode.status==2){
                    return {color:"#dda525", "font-weight":"normal"};
                }else{
                    return {color:"#333", "font-weight":"normal"};
                }
            }else{
                return {color:"#A60000", "font-weight":"bold"};
            }
        }
    },
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true,
            idKey:'id',
            pIdKey:'parentId',
            rootPId:null
        },
        key:{
            name :'subjectName',
            title :'subjectName'
        }
    },
    edit: {
        enable: true,
        showRemoveBtn:false,
        removeTitle:function (treeId,treeNode) {
            return "删除："+treeNode.subjectName;
        },
        renameTitle:function (treeId,treeNode) {
            return "修改："+treeNode.subjectName;
        }
    },
    callback:{
        //用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作
        beforeDrop:updateSubjectParnet,
        //初始化修改
        beforeEditName:initUpdateSubject,
        //用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
        beforeRemove:initDeleteSubject,
        //异步加载数据错误
        onAsyncError: function () {
            icModale(0, "系统错误，专业/科目获取失败");
        },
        onAsyncSuccess: function (event, treeId) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var arr = treeObj.getNodes();
            if(arr && arr.length>0){
                var node = arr[0];
                treeObj.expandNode(node,true,true,true);
            }else{
                setNotDataMsg();
            }
            initCount();
        }
    }
};
//如果没有专业数据显示
function setNotDataMsg() {
    $("#subject-jstree").html('<p id="not-data-msg"><span class="c-4e fs16">亲，还没有创建专业/科目结构~~~</span></p>');
}
/**
 * 初始化专业/科目数量
 */
function initCount() {
    var count = getCount("subject-jstree");
    $('#subject-coun').html('共' + count + '个专业/科目');
}

$(function() {
    //初始化树结构
    $.fn.zTree.init($("#subject-jstree"), setting);

    allSelete('all-subject',function (status) {
        var treeObj = $.fn.zTree.getZTreeObj("subject-jstree");
        treeObj.checkAllNodes(status);
    });
    //添加加
    $("body").on('click',"#add-subject",function () {
        initUpdateOrAdd(0,0);
    });
    $("body").on("click","#delete-subject",function () {//批量删除
        var subjectIds = getCheckedNodesIds();
        if(subjectIds==null || $.trim(subjectIds)==''){
            icModale(0,"请勾选要删除的专业/科目节点！");
            return;
        }
        icModale(2,"确认要删除选中的专业/科目？",3,function () {
            updateSubjectStatus(subjectIds,3);
        });
    }).on("click","#disable-subject",function () {//批量禁用
        var subjectIds = getCheckedNodesIds();
        if(subjectIds==null || $.trim(subjectIds)==''){
            icModale(0,"请勾选要禁用的专业/科目节点！");
            return;
        }
        icModale(2,"确认要禁用选中的专业/科目？",3,function (){
            updateSubjectStatus(subjectIds,2);
        });
    }).on('click','#recovery-subject',function () {//批量恢复
        var subjectIds = getCheckedNodesIds();
        if(subjectIds==null || $.trim(subjectIds)==''){
            icModale(0,"请勾选要恢复的专业/科目节点！");
            return;
        }
        icModale(2,"确认要恢复选中的专业/科目？",3,function (){
            updateSubjectStatus(subjectIds,1);
        });
    }).on("keyup","#search-subject",function () {//专业高亮搜索
        var keyword = this.value;
        var treeObj = $.fn.zTree.getZTreeObj("subject-jstree");
        var list = treeObj.getNodesByFilter(function (node) {
            return true;
        });

        if(!$.isEmptyObject(list) && list.length>0){
            $.each(list,function (index,node){
                node.highlight  = false;
                treeObj.updateNode(node);
            });
        }
        var nodes = treeObj.getNodesByFilter(function (node) {
            if(!$.isEmptyObject(keyword) && $.trim(keyword)!='' && node.subjectName.indexOf(keyword)!=-1){
                return true;
            }else{
                return false;
            }
        });
        if(!$.isEmptyObject(nodes) && nodes.length>0){
            $.each(nodes,function (index,node) {
                node.highlight=true;
                treeObj.updateNode(node);
                treeObj.expandNode(node,true,true,true);
                var parentNode = node.getParentNode();
                if(parentNode!=null){
                    treeObj.expandNode(parentNode,true,true,true);
                }
            });
        }
    });
});
/**
 * 获取勾选状态的节点ID串（半选中不获取）
 * @returns {string}
 */
function getCheckedNodesIds() {
    var treeObj = $.fn.zTree.getZTreeObj("subject-jstree");
    var nodes = treeObj.getCheckedNodes(true);
    if(!$.isEmptyObject(nodes) && nodes.length>0){
        var subjectIds = '';
        $.each(nodes,function (index,em) {
            if(em.check_Child_State ==-1 || em.check_Child_State == 2 ){
                subjectIds+=em.id+',';
            }
        });
        return subjectIds;
    }
    return '';
}
/**
 * 进入修改前
 * @param treeId
 * @param treeNode
 */
function initUpdateSubject(treeId, treeNode) {
    initUpdateOrAdd(0,treeNode.id);
    return false;
}

/**
 * 初始化删除节点
 * @param treeId
 * @param treeNode
 */
function initDeleteSubject(treeId,treeNode){
    icModale(2,"确认要删除专业/科目【"+treeNode.subjectName+"】及子级数据？",3,function () {
        return updateSubjectStatus(treeNode.id,3);
    });
    return false;
}

/**
 * 修改专业节点状态
 * @param ids
 * @param status
 * @returns {boolean}
 */
function updateSubjectStatus(ids,status) {
    var s =false;
    $.ajax({
        url:baseloaction + '/admin/manage/subject/updateSubjectStatus',
        type:'post',
        dataType:'json',
        data:{'ids':ids,'status':status},
        success:function (result) {
            s = result.success;
            if(s){
                var treeObj = $.fn.zTree.getZTreeObj("subject-jstree");
                var arr = (ids+"").split(",");
                $.each(arr,function (index,em) {
                    if(!$.isEmptyObject(em)){
                        var node = treeObj.getNodeByParam("id",em,null);
                        if(status == 3){//删除
                            treeObj.removeNode(node);
                            initCount();//设置显示数量
                            var count = getCount("subject-jstree");
                            if(count <= 0){
                                setNotDataMsg();
                            }
                        }else if(status==2){//禁用
                            if(node.subjectName.lastIndexOf('(禁用)') == -1){
                                node.subjectName = node.subjectName+'(禁用)';
                            }
                            node.status=2;
                            treeObj.updateNode(node);
                        }else if(status ==1){//恢复
                            node.subjectName = node.subjectName.replace(/\(禁用\)/g,'');
                            node.status=1;
                            //恢复父级目录
                            var nodeParent =  node.getParentNode() ;
                              if(nodeParent!=null){
                                  nodeParent.subjectName = nodeParent.subjectName.replace(/\(禁用\)/g,'');
                                  nodeParent.status=1;
                                  treeObj.updateNode(nodeParent);
                              }
                            treeObj.updateNode(node);
                        }
                    }
                });
            }
            icModale(0, result.message);

        },
        error:function (error) {
            icModale(0, "系统错误，操作失败");
        }
    });
    return s;
}

/**
 * 编辑专业/科目节点
 * @param parentId 父ID，没有父ID可以传0
 * @param subjectId 专业ID
 */
function initUpdateOrAdd(parentId,subjectId) {
    var title = "修改专业/科目";
    var url = baseloaction + "/admin/manage/subject/initUpdate?id="+subjectId;
    var status = false;
    if(subjectId==0){
        title = "新建专业/科目"
        url = baseloaction + "/admin/manage/subject/initAdd?parentId="+parentId;
        status = true;
    }
    // var context = "";
    // $.ajax({
    //     url:url,
    //     type:'post',
    //     dataType:'text',
    //     async:false,
    //     success:function(result){
    //         context = result;
    //     },
    //     error:function(error){
    //         icModale(0, "系统错误，操作失败");
    //     }
    // });

    parent.layer.open({
        type: 2,
        title: '<strong>'+title+'</strong><small class="ml10"></small>',
        maxmin: true, //开启最大化最小化按钮
        btn:["确认保存","取消"],
        skin: 'layui-layer-demo',
        area: winArea,
        content: url,
        yes: function(index, layero){
            var body = parent.layer.getChildFrame('body', index);
            var params = body.find("form").serializeJSON();
            setSortNum(params,subjectId,parentId)
            params = JSON.stringify(params);
            $.ajax({
                url: baseloaction +'/admin/manage/subject/saveSubject',
                contentType:'application/json;charset=utf-8',
                type:'post',
                dataType:'json',
                data:params,
                success:function (result) {
                    if(result.success==true){
                        /*var subject = result.entity;
                        var treeObj = $.fn.zTree.getZTreeObj("subject-jstree");
                        if(status==false){//修改节点
                            var nodeList = treeObj.getNodesByParam("id",subject.id,null);
                            if(subject.status==1){
                                nodeList[0].subjectName = subject.subjectName;
                            }else{
                                nodeList[0].subjectName = subject.subjectName+'(禁用)';
                            }
                            nodeList[0].status = subject.status;
                            treeObj.updateNode(nodeList[0]);
                        }else{//添加节点
                            var parentId = result.parentId;
                            var parentNode = null;
                            if(parentId!=null){
                                var nodeList = treeObj.getNodesByParam("id",parentId,null);
                                if(nodeList!=null && nodeList.length > 0){
                                    parentNode = nodeList[0];
                                }
                            }
                            var nodes = new Array();
                            nodes.push(subject);
                            treeObj.addNodes(parentNode,nodes);
                            //重新初始化显示数量
                            initCount();
                            $("#not-data-msg").remove();
                        }*/
                        parent.layer.close(index);
                        window.location.href = baseloaction +'/admin/manage/subject/toSubjectList';
                    }else{
                        icModale(0, result.message);
                    }
                },
                error:function (error) {
                    icModale(0, "系统错误，保存专业/科目失败");
                }
            });
        }
    });
}

/**
 * 节点拖拽时，修改节点的父级ID
 * @param treeId 树结构的ID
 * @param treeNodes 被拖拽的节点
 * @param targetNode 目标节点
 * @param moveType 拖拽类型
 * @returns {boolean} true拖拽成功，false拖拽失败
 */
function updateSubjectParnet(treeId, treeNodes, targetNode, moveType) {
    var node = treeNodes[0];
    if(node.isParent){
        icModale(0,"包含子级科目的专业不能移动");
        return false;
    }
    if((targetNode.level+2)>2){
        icModale(0,"专业/科目最多有二级关联");
        return false;
    }
    var parentId = 0;
    if(moveType=='prev'){//移动到目标节点上面，如果目标节点没有父级则把移动的的父ID设置成0，如果目标节点有父ID则把该父ID设置成远去节点的父ID
        var parent = targetNode.getParentNode();
        if(!$.isEmptyObject(parent)){
            parentId = parent.id;
        }
    }else if(moveType=='inner' || moveType=='next'){//移动到目标节点下面，则把目标节点的ID设置被移动节点的父ID
        parentId = targetNode.id;
    }
    var s = true;
    $.ajax({
        url: baseloaction + '/admin/manage/subject/updateSubjectParentId',
        type:'post',
        dataType:'json',
        async:false,
        data:{'subjectId':node.id,'parentId':parentId},
        success:function (result) {
            s = result.success;
            if(s==false){
                icModale(0,result.message);
            }
        },
        error:function (error) {
            s = false;
            icModale(0,"系统错误专业/科目移动失败");
        }
    });
    //去保存
    return s;
}


/**
 * 修改排序
 * @param currentId 要操作的节点ID
 * @param currentSort 操作的节点的新排序
 * @param oldId 被替换节点的ID
 * @param oldSort 被替换节点的排序
 * @param type 类型，1向前，2向后
 */
function updateNodeSort(currentId,currentSort,oldId,oldSort,type) {
    $.ajax({
        url: baseloaction +'/admin/manage/subject/updateNodeSort',
        type:'post',
        dataType:'json',
        data:{
            'currentId':currentId,
            'currentSort':currentSort,
            'oldId':oldId,
            'oldSort':oldSort
        },
        success:function (result) {
            if(result.success==true){
                var zTree = $.fn.zTree.getZTreeObj('subject-jstree');
                var currentNode = zTree.getNodeByParam('id', currentId, null);
                currentNode.sort = currentSort;
                var oldNode = zTree.getNodeByParam('id', oldId, null);
                oldNode.sort = oldSort;
                zTree.updateNode(currentNode);
                zTree.updateNode(oldNode);
                if(type==1){//1向前
                    zTree.moveNode(oldNode, currentNode, "prev");
                }
                if(type==2){//2向后
                    zTree.moveNode(oldNode, currentNode, "next");
                }
                zTree.cancelSelectedNode(currentNode);
            }else{
                icModale(0,result.message);
            }
        },
        error:function (error) {
            icModale(0,'系统错误，调整节点排序失败');
        }
    });
}


/**
 * 设置排序
 * @param params 参数对象
 * @param id
 * @param parentId
 */

function setSortNum(params,id,parentId) {
    if(id <= 0){//表示添加
        var sort=0;
        if($(".ibox-content-tree")!=undefined&&$(".ibox-content-tree")!=null){
            sort =  $(".ibox-content-tree").find("li").length
        }
        params.sort = sort;
    }
}


